package com.example.safeassistan.my.index;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.safeassistan.R;
import com.example.safeassistan.UserInfoModel;
import com.example.safeassistan.base.BaseModel;
import com.example.safeassistan.base.BaseVPFragment;
import com.example.safeassistan.common.MethodUtils;
import com.example.safeassistan.common.UserData;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.message.activity.Activity_Message;
import com.example.safeassistan.my.activity.ActivityPhone;
import com.example.safeassistan.my.activity.CodeInput_Activity;
import com.example.safeassistan.my.activity.FeedbackListActivity;
import com.example.safeassistan.my.activity.HistoryTaskList;
import com.example.safeassistan.utile.APKVersionCodeUtils;
import com.example.safeassistan.utile.GlideEngine;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.utile.PictureUtils;
import com.example.safeassistan.utile.ToastUtil;
import com.example.safeassistan.widget.PhotoPickBottomDialog;
import com.example.safeassistan.widget.WarningDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.app.Activity.RESULT_OK;

public class MyIndex extends BaseVPFragment implements View.OnClickListener {

private View view;
private Context context;
private LinearLayout llExitApp,llFeedbackList,llPassword,llHistoryTask,llPhone,llVersion;
private ImageView ivHeadPhoto;
private TextView tvNickName,tvPhone,tvDepartment,tvDegree,tvVersionCode;
private LinearLayout llEditHeadPhoto;
private ImageView ivMsg;

    public static MyIndex newInstance(String content) {
        Bundle arguments = new Bundle();
        arguments.putString("string", content);
        MyIndex fl = new MyIndex();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_my_index, container, false);
            context = getActivity();
            initView();
        }
        return view;
    }

    private void initView() {
        tvDepartment=view.findViewById(R.id.tvDepartment);
        ivMsg=view.findViewById(R.id.ivMsg);
        llExitApp=view.findViewById(R.id.llExitApp);
        llExitApp.setOnClickListener(this::onClick);
        tvVersionCode=view.findViewById(R.id.tvVersionCode);
        llFeedbackList=view.findViewById(R.id.llFeedbackList);
        llFeedbackList.setOnClickListener(this::onClick);
        ivHeadPhoto=view.findViewById(R.id.ivHeadPhoto);
        llVersion=view.findViewById(R.id.llVersion);
        llPassword=view.findViewById(R.id.llPassword);
        tvDegree=view.findViewById(R.id.tvDegree);
        llPassword.setOnClickListener(this::onClick);
        tvNickName=view.findViewById(R.id.tvNickName);
        llHistoryTask=view.findViewById(R.id.llHistoryTask);
        llHistoryTask.setOnClickListener(this::onClick);
        llEditHeadPhoto=view.findViewById(R.id.llEditHeadPhoto);
        llPhone=view.findViewById(R.id.llPhone);
        tvPhone=view.findViewById(R.id.tvPhone);
        llVersion.setOnClickListener(this::onClick);
        llEditHeadPhoto.setOnClickListener(this::onClick);
        ivMsg.setOnClickListener(this::onClick);
        llPhone.setOnClickListener(this::onClick);
        tvVersionCode.setText(APKVersionCodeUtils.getVerName(context));
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onFragmentFirstVisible() { }
    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if(isVisible){
            getUserInfo();
        }
    }

    public  void submit(String headImg) {
        Map map = new HashMap<>();
        map.put("Img", headImg);
        new HttpRequest(context).doGet(UrlConstants.userInfoupdatePicture, null, map,new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                String data = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                       //上传成功
                        getUserInfo();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.e("MyIndex",msg);
            }
        });
    }

    public  void getUserInfo() {
        new HttpRequest(context).doGet(UrlConstants.userInfoqueryPersonage, null,new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), UserInfoModel.class);
                        if (obj instanceof UserInfoModel) {
                            UserInfoModel model = (UserInfoModel) obj;
                            UserData.create(context).saveUserData(model.getResult());
                            Glide.with(context)
                                    .load(UserData.create(context)
                                            .get(UserData.AVATAR))
                                    .placeholder(R.mipmap.icon_headlink)
                                    .apply(new RequestOptions().transform(new PictureUtils()))
                                    .into(ivHeadPhoto);
                            tvNickName.setText(UserData.create(context).get(UserData.REALNAME));
                            tvPhone.setText(UserData.create(context).get(UserData.PHONE));
                            tvDepartment.setText(UserData.create(context).get(UserData.DEPARTMENTNAME));
                            tvDegree.setText(UserData.create(context).get(UserData.POSTNAME));
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llVersion:
                //ba版本升级

                break;
            case R.id.llPhone:
                //手机号
                ActivityPhone.actionStart(context);
                break;
            case R.id.ivMsg:
                //消息
                Activity_Message.actionStart(context);
                break;
            case R.id.llHistoryTask:
                //历史任务
                HistoryTaskList.actionStart(context);
                break;
            case R.id.llPassword:
                //密码设置修改相关
                CodeInput_Activity.actionStart(context,UserData.create(context).get(UserData.PHONE));
                break;
            case R.id.llFeedbackList:
                //反馈列表
                FeedbackListActivity.actionStart(context);
                break;
            case R.id.llExitApp:
                //退出登录
                WarningDialog dialog=new WarningDialog(context,"是否退出登录？","取消","确定","");
                dialog.setClicklistener(new WarningDialog.ClickListenerInterface() {
                    @Override
                    public void doCancel() {
                        dialog.dismiss();
                    }

                    @Override
                    public void doConfirm() {
                        //确定退出登录
                        exitLogin();
                        dialog.dismiss();
                    }
                });
                dialog.show();
                break;
            case R.id.llEditHeadPhoto:
                //编辑图片
                PhotoPickBottomDialog pickBottomDialog=new PhotoPickBottomDialog();
                pickBottomDialog.setClicklistener(new PhotoPickBottomDialog.ClickListenerInterface() {
                    @Override
                    public void takePhoto() {
                        //拍照并剪裁
                        PictureSelector.create((Activity) context)
                                .openGallery(PictureMimeType.ofImage())
                                .selectionMode(PictureConfig.SINGLE)
                                .isCamera(true)
                                .compressQuality(100)
                                .compress(true)
                                .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                .forResult(PictureConfig.REQUEST_CAMERA);
                    }

                    @Override
                    public void selectFromAlbum() {
                        PictureSelector.create((Activity) context)
                                .openGallery(PictureMimeType.ofImage())
                                .selectionMode(PictureConfig.SINGLE)
                                .isCamera(false)
                                .compressQuality(100)
                                .compress(true)
                                .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    }
                });
                pickBottomDialog.show(getChildFragmentManager());
                break;
        }
    }

    String path="";
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                case PictureConfig.REQUEST_CAMERA:
                    // 结果回调
                    List<LocalMedia> cameraList = PictureSelector.obtainMultipleResult(data);
                    if(cameraList.size()>0){
                        path=cameraList.get(0).getRealPath();
                    }
                    Glide.with(context).load(path)
                            .placeholder(R.mipmap.icon_headlink)
                            .apply(new RequestOptions().transform(new PictureUtils()))
                            .into(ivHeadPhoto);
                    uploadImg(path);
                    break;
                default:
                    break;
            }
        }
    }

    public void uploadImg(String path){
        new HttpRequest(context).doUploadFile(UrlConstants.commonupload, "", "file", new File(path), new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model=(BaseModel) obj;
                            submit(model.getMessage());
                        }
                    }else {
                        ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, message, 1);
                        toastUtil.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }

    public  void exitLogin() {
        new HttpRequest(context).doPost(UrlConstants.exitLogin, null,new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                String data = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        MethodUtils.logoutAfter(context);
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.e("MyIndex",msg);
            }
        });
    }
}